package com.lminkey.servlet;

import com.lmonkey.dao.Basedao;
import com.lmonkey.dao.MD5;
import com.lmonkey.servic.USERDao;
import com.lmonkey.shop.USER;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpCookie;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/admin/login")
public class Login extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符集
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        String username = request.getParameter("username");
        String pass = request.getParameter("pass");
        String pass1 = null;

        Connection conn = Basedao.getconn();
        PreparedStatement ps = null;
        ResultSet rs = null;
        int count = 0;
        //在数据库中查询数据
        try {
            pass1 = MD5.md5(pass);
            String sql = "select count(*) from lmonkeyshop where user_id=? and user_pass = ?";
            ps = conn.prepareStatement(sql);
            ps.setObject(1,username);
            ps.setObject(2,pass1);
            rs = ps.executeQuery();
            while (rs.next()){
                count = rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (count>0){
            HttpSession session = request.getSession();
            USER user = USERDao.selectAdmin(username,pass1);
            session.setAttribute("name",user);
            session.setAttribute("isLogin","1");
            //cookie操作
            Cookie ck1 = new Cookie("username",username);
            ck1.setMaxAge(60 * 60 * 24 * 10);
            response.addCookie(ck1);
            Cookie ck2 = new Cookie("password",pass);
            ck2.setMaxAge(60 * 60 * 24 * 10);
            response.addCookie(ck2);

            response.sendRedirect("http://localhost:8080/lyq/shangc/indexselect");
        }else{
            //清除cookie
            Cookie[] cks = request.getCookies();
            if (cks !=null){
                for (Cookie c : cks){
                    c.setMaxAge(0);
                    response.addCookie(c);
                }
            }
            //跳转页面
            PrintWriter out = response.getWriter();
            out.println("<script>alert('用户名或密码错误');location.href='/lyq/shangc/login.jsp';</script>");
            out.close();
        }
    }
}
